package com.sardine.base.esm.builder;


import com.sardine.base.esm.session.Configuration;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.builder.IncompleteElementException;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

/**
 * 上海京东到家元信信息技术有限公司<br>
 * Created with IntelliJ IDEA.
 * Date:2017/5/23
 * Time:16:35
 *
 * @author daifeng<br>
 *         daifeng@imdada.cn
 * @since JDK 1.7 <br>
 * Copyright (c) 2017 imdada System Incorporated All Rights Reserved.
 */
public class EsmMapperAnnotationBuilder {
    private static final Logger logger = LoggerFactory.getLogger(EsmMapperAnnotationBuilder.class);

    private final Set<Class<? extends Annotation>> esmAnnotationTypes = new HashSet<Class<? extends Annotation>>();
    private final Set<Class<? extends Annotation>> esmProviderAnnotationTypes = new HashSet<Class<? extends Annotation>>();

    private Configuration configuration;
    private Class<?> type;

    public EsmMapperAnnotationBuilder(Configuration configuration, Class<?> type) {
        this.configuration = configuration;
        this.type = type;
        esmAnnotationTypes.add(Select.class);
        esmAnnotationTypes.add(Insert.class);
        esmAnnotationTypes.add(Update.class);
        esmAnnotationTypes.add(Delete.class);
    }
    public void parse() {
        String resource = type.toString();
        if (!configuration.isResourceLoaded(resource)) {
            configuration.addLoadedResource(resource);
            Method[] methods = type.getMethods();
            for (Method method : methods) {
                try {
                    parseStatement(method);
                } catch (IncompleteElementException e) {
//                    configuration.addIncompleteMethod(new MethodResolver(this, method));
                }
            }
        }
    }

    void parseStatement(Method method) {
        Class<?> parameterTypeClass = getParameterType(method);
    }

    private Class<?> getParameterType(Method method) {
        Class<?> parameterType = null;
        Class<?>[] parameterTypes = method.getParameterTypes();
        for (int i = 0; i < parameterTypes.length; i++) {
            if (!RowBounds.class.isAssignableFrom(parameterTypes[i]) && !ResultHandler.class.isAssignableFrom(parameterTypes[i])) {
                if (parameterType == null) {
                    parameterType = parameterTypes[i];
                } else {
                    parameterType = MapperMethod.ParamMap.class; // issue #135
                }
            }
        }
        return parameterType;
    }
}
